package com.trw.trp.util;

import java.util.Map;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionContext;
import com.trw.trp.bean.ModelBean;
import com.trw.trp.bean.ModelDetail;
import com.trw.trp.bean.OrderBean;
import com.trw.trp.dao.DaoFactory;
import com.trw.trp.dao.SystemSettingDao;
import com.utuan.log.Log;
import com.utuan.log.LogFactory;

public class TRPUtil {

	private static Log log = LogFactory.getLog(TRPUtil.class);

	public static void setToRequest(String key, Object value) {
		HttpServletRequest request = ServletActionContext.getRequest();
		if (request != null) {
			request.setAttribute(key, value);
		}
	}

	public static ModelBean getCurrentModel() {
		ModelBean model = null;
		OrderBean order = (OrderBean) getFromSession(TRPConstants.CURRENT_ORDER);
		Integer currentStatus = (Integer) getFromSession(TRPConstants.CURRENT_MODEL_STATUS);
		Integer currentModelIdx = (Integer) getFromSession(TRPConstants.CURRENT_MODEL_IDX);
		if (currentStatus == null) {
			currentStatus = 1;
		}
		if (currentModelIdx == null) {
			currentModelIdx = 0;
		}
		if (order != null) {
			model = order.getModelMap().get(currentStatus).get(currentModelIdx);
		}
		return model;
	}

	public static ModelDetail getCurrentModelDetail() {
		ModelDetail detail = null;
		OrderBean order = (OrderBean) getFromSession(TRPConstants.CURRENT_ORDER);
		Integer currentStatus = (Integer) getFromSession(TRPConstants.CURRENT_MODEL_STATUS);
		Integer currentModelIdx = (Integer) getFromSession(TRPConstants.CURRENT_MODEL_IDX);
		if (currentStatus == null) {
			currentStatus = 1;
		}
		if (currentModelIdx == null) {
			currentModelIdx = 0;
		}
		if (order != null) {
			detail = order.getDetailMap().get(currentStatus)
					.get(currentModelIdx);
		}
		return detail;
	}

	public static void putToSession(String key, Object value) {
		Map<String, Object> session = getSession();
		if (session != null) {
			session.put(key, value);
		}
	}

	public static Object getFromSession(String key) {
		Map<String, Object> session = getSession();
		if (session != null) {
			return session.get(key);
		}
		return null;
	}

	public static void removeFromSession(String key) {
		Map<String, Object> session = getSession();
		if (session != null) {
			session.remove(key);
		}
	}

	private static Map<String, Object> getSession() {
		ActionContext actionContext = ActionContext.getContext();
		Map<String, Object> session = actionContext.getSession();
		return session;
	}

	public static long parseOrderId(OrderBean order) {
		long orderId = -1;
		if (order != null && order.getOrderNumber() != null) {
			try {
				String orderIdStr = order.getOrderNumber().substring(7);
				orderId = Long.parseLong(orderIdStr);
			} catch (Exception e) {
				log.warn(e);
			}
		}
		return orderId;
	}

	public static String generateOrderNumber(int year, int autoNumber) {
		StringBuilder orderNumber = new StringBuilder();
		try {
			orderNumber.append("TRP").append(year).append(fill0(autoNumber));
		} catch (Exception e) {
			log.warn(e);
		}
		return orderNumber.toString();
	}

	private static String fill0(long orderId) {
		StringBuilder sb = new StringBuilder();
		sb.append(orderId);
		while (sb.length() < 4) {
			sb.insert(0, "0");
		}
		return sb.toString();
	}

	@SuppressWarnings("static-access")
	public static void sendMail(String toUser, String ccUser, String subject,
			String body) throws MessagingException {
		SystemSettingDao dao = DaoFactory.getSystemSettingDao();
		Properties props = new Properties();
		props.put("mail.smtp.host", dao.getProperty(1) == null ? null : dao
				.getProperty(1).getValue());
		props.put("mail.smtp.auth", true);
		MyAuthenticator myauth = new MyAuthenticator(
				dao.getProperty(2) == null ? null : dao.getProperty(2)
						.getValue(), dao.getProperty(3) == null ? null : dao
						.getProperty(3).getValue());
		Session sendMailSession = Session.getInstance(props, myauth);
		Message newMessage = new MimeMessage(sendMailSession);
		newMessage.setFrom(new InternetAddress(
				dao.getProperty(4) == null ? null : dao.getProperty(4)
						.getValue()));
		String toUsers[] = toUser.split(TRPConstants.COMMA);
		InternetAddress[] toUserAddrs = new InternetAddress[toUsers.length];
		for (int i = 0; i < toUsers.length; i++) {
			toUserAddrs[i] = new InternetAddress(toUsers[i]);
		}
		String[] ccUsers = null;
		if (!StringUtils.isEmpty(ccUser)) {
			ccUsers = ccUser.split(TRPConstants.COMMA);
			InternetAddress[] ccUserAddrs = new InternetAddress[ccUsers.length];
			for (int i = 0; i < toUsers.length; i++) {
				if (ccUsers[i].trim().length() > 0) {
					ccUserAddrs[i] = new InternetAddress(ccUsers[i]);
				}
			}
			newMessage.setRecipients(Message.RecipientType.CC, ccUserAddrs);
		}
		newMessage.setRecipients(Message.RecipientType.TO, toUserAddrs);
		newMessage.setSubject(subject);
		newMessage.setContent(body, "text/html; charset=UTF-8");
		Transport transport = sendMailSession.getTransport("smtp");
		transport.send(newMessage, newMessage.getAllRecipients());
		transport.close();
	}

	static class MyAuthenticator extends javax.mail.Authenticator {
		private String strUser;
		private String strPwd;

		public MyAuthenticator(String user, String password) {
			this.strUser = user;
			this.strPwd = password;
		}

		protected PasswordAuthentication getPasswordAuthentication() {
			return new PasswordAuthentication(strUser, strPwd);
		}
	}

	public static void main(String[] args) {
		System.out.println(TRPConstants.DATE_FORMAT2
				.format(new java.util.Date()));
	}

	public static String generateSDNumber(int year, int autoNumber) {
		StringBuilder orderNumber = new StringBuilder();
		try {
			orderNumber.append("SD").append(year).append(fill0(autoNumber));
		} catch (Exception e) {
			log.warn(e);
		}
		return orderNumber.toString();
	}
}
